package com.cskaoyan.config.shiro;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;
import java.util.LinkedHashMap;

/**
 * @Description: Shiro框架配置
 * @Author: Pinocao
 * @CreateTime: 2022-11-21  17:20
 * @Version: 1.0
 */
@Configuration
public class ShiroConfiguration {
    // ShiroFilter → SecurityManager
    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 提供对应的Filter链，此处需保证map有序所以使用LinkedHashMap，map中的key代表URL，value代表Filter名称
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        // 映射关系顺序anon、authc、perms
        linkedHashMap.put("/admin/auth/login","anon");
        linkedHashMap.put("/admin/auth/logout","anon");
        linkedHashMap.put("/admin/auth/noAuthc","anon");
        linkedHashMap.put("/admin/**","authc");
        // 用户部分
        linkedHashMap.put("/wx/auth/login","anon");
        linkedHashMap.put("/wx/auth/logout","anon");
        linkedHashMap.put("/wx/**","anon");
        // linkedHashMap.put("/wx/**","authc");
        // 未通过认证自动跳转
        shiroFilterFactoryBean.setLoginUrl("/admin/auth/noAuthc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(linkedHashMap);
        return shiroFilterFactoryBean;
    }

    // SecurityManager → Authenticator 可以使用默认的、Authorizer 可以使用默认的、 ..
    @Bean
    public DefaultWebSecurityManager securityManager(Collection<Realm> realms, DefaultWebSessionManager sessionManager, CustomModularRealmAuthenticator customModularRealmAuthenticator) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 如果要使用自定义的认证器和授权器，需要在这里调用对应的set方法
        securityManager.setAuthenticator(customModularRealmAuthenticator);
        securityManager.setRealms(realms);
        securityManager.setSessionManager(sessionManager);
        return securityManager;
    }

    // Realms，可以在实现的Realm类上增加@Component注解注册组件，也可以使用@Bean注册
    // SessionManager
    @Bean
    public DefaultWebSessionManager sessionManager() {
        // 向容器中注册SessionManage
        return new MarketSessionManage();
    }

}